import {
  FormControl,
  FormField,
  useFieldContext,
  type ValueAccessibleComponent,
  type ValueAccessor,
} from "solid-form-context";
import {
  createMemo,
  splitProps,
  type ComponentProps,
  type ValidComponent,
} from "solid-js";
import type { FcFormItemProps } from "./types";
import Slot from "@lib/Slot";
import {
  convertLayoutTemplate,
  useFcFormItemLayoutContext,
} from "../FcFormItemLayout";
import { wrapClasses } from "@lib/types";

const FcFormItem = <
  V,
  C extends ValueAccessibleComponent<V, ValueAccessor<V>> | ValidComponent,
  P extends ComponentProps<C>,
  K extends keyof P
>(
  props: FcFormItemProps<V, C, P, K>
) => {
  const [local, fieldProps] = splitProps(props, [
    "label",
    "layout",
    "classList",
  ]);

  const layoutContext = useFcFormItemLayoutContext();

  const field = <FormField {...fieldProps}></FormField>;

  const layout = createMemo(() => {
    return {
      ...layoutContext,
      ...local.layout,
    };
  });

  return (
    <Slot
      slot={convertLayoutTemplate(layout().template)}
      context={{
        label: local.label,
        field: field,
        classList: {
          ...wrapClasses(layout().classList),
          ...wrapClasses(local.classList),
        },
      }}
    >
      {(ctx) => (
        <div classList={ctx.classList}>
          {ctx.field}
          {ctx.label}
        </div>
      )}
    </Slot>
  );
};

export default FcFormItem;

export * from "./types";
